package me.w70.bot.account;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

import me.w70.bot.Bot;
import me.w70.bot.util.Files;

public class AccountHandler {

	private HashMap<String, Account> accounts = new HashMap<String, Account>();

	public AccountHandler() {
		loadAccounts();
		saveAccounts();
	}

	public void clearAccounts() {
		accounts.clear();
	}

	public void saveAccounts() {
		try {
			Files.setContents(new File(Bot.CONFIG_DIR + "/accounts"),
					makeWrite());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void addAccount(String username, String password) {
		if (username == null || username.equals("") || password == null
				|| password.equals("")) {
			return;
		}
		if(accounts.containsKey(username)) {
			return;
		}
		accounts.put(username, new Account(username, password));
	}
	
	public void removeAccount(String username) {
		if(!accounts.containsKey(username)) {
			return;
		}
		accounts.remove(username);
		Bot.addMessage(this, "Removed account '" + username + "'");
		System.out.println(accounts);
	}

	public HashMap<String, Account> getAccounts() {
		return accounts;
	}

	public void loadAccounts() {
		String file = Files.getContents(new File(Bot.CONFIG_DIR + "/accounts"));
		String[] accountsStr = file.split("\n");
		for (String account : accountsStr) {
			try {
				String[] p = account.split("\\|");
				String username = p[0];
				String password = "";
				if (p.length == 2) {
					password = p[1];
				} else {
					for (int i = 1; i < p.length; i++) {
						password += p[i];
					}
				}
				if (username != null && username != "" && password != null
						&& password != "") {
					accounts.put(username, new Account(username, password));
				}
			} catch (Exception e) {

			}
		}
	}

	public String makeWrite() {
		String w = "";
		for (String username : accounts.keySet()) {
			w += username + "|" + accounts.get(username).getPassword() + "\n";
		}
		try {
		w = w.substring(0, w.length() - 1);
		}catch(Exception e) {
			return ""; //no accounts
		}
		return w;
	}

}
